package com.example.springboot3.utils;


import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.springboot3.common.Constants;
import com.example.springboot3.common.enums.RoleEnum;
import com.example.springboot3.entity.Account;
import com.example.springboot3.service.AdminService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.condition.RequestConditionHolder;

import java.util.Date;

/**
 * token工具类
 */
@Component
public class TokenUtils {
//    打印日志
    private static final Logger log = LoggerFactory.getLogger(TokenUtils.class);

    @Resource
    private AdminService adminService;

//    写一个静态的成员变量
    private static AdminService staticAdminService;

//    在初始化的时候赋值
    @PostConstruct
    public void init(){
        staticAdminService = adminService;
    }

    /**
     * 生成jwt的token
     * @param data
     * @param sign
     * @return
     */
    public static String createToken(String data, String sign){
//        audience是存储数据的一个媒介 存储用户ID和用户角色 通过角色才知道从哪个表里面去查
        return JWT.create().withAudience(data)
                .withExpiresAt(DateUtil.offsetDay(new Date(),1))  //偏移一天  过期时间1天
                .sign(Algorithm.HMAC256(sign))  //对传入的密钥进行加密
        ;
    }

//    获取当前登录的用户
    public static Account getCurrentUser() {
        try{
            //        为什么要在前面加一个类型
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader(Constants.TOKEN);
//       解析
            String audience = JWT.decode(token).getAudience().get(0);  //因为是一个数组 所以用get(0)
            String[] userRole = audience.split("-");
            Integer userId = Integer.valueOf(userRole[0]);
            String role = userRole[1];
            if (RoleEnum.ADMIN.name().equals(role)) {
//            这个在外面定义了才能调用
                return staticAdminService.selectById(userId);
            }
        }catch (Exception e){
            log.error("获取当前用户失败",e);
        }
        return null;
    }
}
